package chapter22;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/26 17:05
 */
public class SimpleContainer implements ISimpleContainer {
    private Map<Class<?>, Object> cache = new ConcurrentHashMap<>();

    @Override
    public <T> T getInstance(Class<T> clazz) {
        boolean flag = clazz.isAnnotationPresent(SimpleSingleton.class);

        if (!flag) {
            return createInstance(clazz);
        }

        if (cache.containsKey(clazz)) {
            return (T) cache.get(clazz);
        }

        T entity = createInstance(clazz);
        cache.put(clazz, entity);
        return entity;
    }

    private <T> T createInstance(Class<?> clazz) {
        try {
            T obj = (T) clazz.newInstance();
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(SimpleInject.class)) {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }

                    field.set(obj, getInstance(clazz));
                }
            }

        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


}
